package com.edu.exam.entity.assessment.technical;

import com.edu.exam.enums.assessment.technical.AnomalySourceModule;
import com.edu.exam.enums.assessment.technical.AnomalySeverityLevel;
import jakarta.persistence.*;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.AllArgsConstructor;
import lombok.experimental.SuperBuilder;

import java.time.LocalDateTime;

/**
 * 异常检测规则实体类
 * 所属模块：B-02 题库管理模块
 * 对应数据库表：anomaly_detection_rule
 *
 * 根据E-06-03质量监控子模块设计实现
 * 对应anomaly_detection_rules数据表，用于存储质量异常检测的规则配置
 *
 * @author System
 * @version 1.0.0
 */
@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
@SuperBuilder
@EqualsAndHashCode(callSuper = false)
public class AnomalyDetectionRule {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;

    @Column(name = "rule_id", length = 32, unique = true, nullable = false)
    private String ruleId;

    @Column(name = "rule_name", length = 100, nullable = false)
    private String ruleName;

    @Column(name = "rule_type", length = 50, nullable = false)
    private String ruleType;

    @Enumerated(EnumType.STRING)
    @Column(name = "source_module", length = 20)
    private AnomalySourceModule sourceModule;

    @Column(name = "rule_expression", columnDefinition = "JSON", nullable = false)
    private String ruleExpression;

    @Column(name = "threshold_config", columnDefinition = "JSON", nullable = false)
    private String thresholdConfig;

    @Enumerated(EnumType.STRING)
    @Column(name = "severity_level", length = 20, nullable = false)
    private AnomalySeverityLevel severityLevel;

    @Column(name = "is_active", nullable = false)
    private Boolean isActive;

    @Column(name = "created_by", length = 32, nullable = false)
    private String createdBy;

    @Column(name = "created_time", nullable = false)
    private LocalDateTime createdTime;

    @Column(name = "updated_by", length = 32)
    private String updatedBy;

    @Column(name = "update_time")
    private LocalDateTime updateTime;

    // 扩展字段
    @Column(name = "description", columnDefinition = "TEXT")
    private String description; // 规则描述

    @Column(name = "category", length = 50)
    private String category; // 规则分类

    @Column(name = "tags", length = 500)
    private String tags; // 标签

    @Column(name = "version")
    private Integer version; // 版本号

    @PrePersist
    protected void onCreate() {
        LocalDateTime now = LocalDateTime.now();
        this.createdTime = now;
        this.updateTime = now;

        // 设置默认值
        if (this.isActive == null) {
            this.isActive = true;
        }
        if (this.version == null) {
            this.version = 1;
        }
    }

    @PreUpdate
    protected void onUpdate() {
        this.updateTime = LocalDateTime.now();
        if (this.version != null) {
            this.version = this.version + 1;
        }
    }

    }
